package com.mew.common.dc.db;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mew.common.config.RedisConstantValue;
import com.mew.common.dc.mapper.MaintenanceMapper;
import com.mew.common.entity.sys.Maintenance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MaintenanceService {

    @Autowired
    private MaintenanceMapper maintenanceMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void addMaintenance(Maintenance m){
//        maintenanceMapper.insert(m);
//        registerFeignService.updateTmsOnlineALL(OnlineType.Unbound.value());
        maintenanceMapper.insert(m);
        redisTemplate.opsForValue().set(RedisConstantValue.CONFIG_MAINTAIN, m.getId());
    }

    public boolean getMaintenance(){
        Object v = redisTemplate.opsForValue().get(RedisConstantValue.CONFIG_MAINTAIN);
        return v != null ? true : false;
    }


    public void updateMaintenance(Integer id,Integer state){
//        Maintenance newb = new Maintenance();
//        newb.setId(id);
//        newb.setState(state==1?0:1);
//        maintenanceMapper.updateById(newb);
//
//        registerFeignService.updateTmsOnlineALL(newb.getState()==1? OnlineType.Unbound.value():OnlineType.Online.value());

        Maintenance newb = new Maintenance();
        newb.setId(id);
        newb.setState(state==1 ? 0 : 1);
        maintenanceMapper.updateById(newb);


        if (newb.getState() == 1){
            addMaintenance(newb);
        }else {
            redisTemplate.delete(RedisConstantValue.CONFIG_MAINTAIN);
        }

    }

    public List<Maintenance> findMaintenance(){
        return maintenanceMapper.selectList(new QueryWrapper<Maintenance>().orderByDesc("id"));
    }

    public Maintenance queryMaintenanceInfo(){

        LambdaQueryWrapper<Maintenance> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Maintenance::getId).last("LIMIT 1");
        return maintenanceMapper.selectOne(wrapper);
    }



}
